package com.smarttest.portal.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smarttest.common.beans.GeneralResult;
import com.smarttest.portal.beans.User;
import com.smarttest.portal.pojo.Authgroup;
import com.smarttest.portal.service.DBUserAuthService;
import com.smarttest.portal.service.impl.DBUserAuthServiceImpl;

@Controller
public class LogController {
	@Autowired
	DBUserAuthService userDBAuthService;

	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	@ResponseBody
	public GeneralResult validateUser(HttpServletRequest request, HttpServletResponse response) {
//		String userName = request.getRemoteUser();
		String userName  = request.getSession().getAttribute("name").toString();
		GeneralResult result;
		List<Authgroup> userAuthority;
		String page = "autog7,autog7report";
		userAuthority = userDBAuthService.selectUserAuthByName(userName);
		if (userAuthority == null || userAuthority.size() == 0) {
			userAuthority = userDBAuthService.createUser(userName);
		}
		if (userAuthority != null && userAuthority.size() > 0) {
			Authgroup group = userAuthority.get(0);
			String pages = group.getPages();
			if (null != pages && pages.length() > 0) {
				page = pages;
			}
			HttpSession session = request.getSession();
			User user = new User();
			user.setUsername(userName);
			user.setAuthority(page);
			session.setAttribute(DBUserAuthServiceImpl.SESSION_FLAG, user);
			session.setMaxInactiveInterval(DBUserAuthServiceImpl.SESSION_TIMEOUT);
			result = GeneralResult.okData("", user);
		} else {
			result = GeneralResult.error("数据库无此用户");
		}
		return result;
	}

	@RequestMapping(value = "/logout.action", method = RequestMethod.GET)
	@ResponseBody
	public GeneralResult LogOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("Enter LogOutController.......");
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(DBUserAuthServiceImpl.SESSION_FLAG);
		if (user != null) {
			session.removeAttribute(DBUserAuthServiceImpl.SESSION_FLAG);
			// 清除cookie
			session.invalidate();
			return GeneralResult.ok(null, "注销成功");
		} else {
			return GeneralResult.error("注销失败");
		}
	}
}
